import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state () {
    return {
      count: 0,
      userInfo: null,
      token: null,
      cname: ''
    }
  },
  mutations: {
    changeCount (state, num) {
      state.count += num
      console.log('mutations执行了，count值为：', state.count)
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
      if (userInfo) {
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
      } else {
        sessionStorage.removeItem('userInfo')
      }
    },
    setToken (state, token) {
      state.token = token
      if (token) {
        console.log('store存储token:', token)
        sessionStorage.setItem('token', JSON.stringify(token))
      } else {
        sessionStorage.removeItem('token')
      }
    },
    setCName (state, cname) {
      state.cname = cname
      if (cname) {
        sessionStorage.setItem('cname', JSON.stringify(cname))
      } else {
        sessionStorage.removeItem('cname')
      }
    }
  },
  getters: {
    // 带有缓存功能，类似计算属性
    len (state) {
      console.log('gettter执行了')
      return state.userInfo
    }
  },
  actions: {
    // 延时3秒触发
    // action 是异步请求
    delayChange (store, num) {
      setTimeout(() => {
        store.commit('changeCount', 5)
        console.log('action触发了，此时count为:', num)
      }, 3000)
    }
  }
})
export default store
